require "proto/market/message/ReqFetchRewardMessage"
require "proto/market/message/ReqSendMarketInfoMessage"
require "proto/market/message/ReqBuyMessage"
require "proto/market/message/ReqChooseGiftMessage"
require "proto/market/message/ReqOneMarketInfoMessage"
require "proto/pay/message/ReqCreatePayOrderMessage"
require "proto/pay/message/ReqPayGradeMessage"
require "proto/pay/message/ReqVoucherDataMessage"
require "proto/pay/message/ReqVoucherBuyMessage"
require "proto/pay/message/ReqFetchVoucherMessage"
require "proto/pay/message/ReqPaySuccessMessage"
require "proto/market/message/ReqCurrencyBuyMessage"


costHandler = costHandler or {};
G.serverData = G.serverData or {};

function costHandler.GetMarketInfo(msg)
    if msg.state == 0 then
        logicMgr.CostManager.resCostServerData(msg.marketDataList);
    end
end

function costHandler.GetFetchRewardMsg(msg)
    if msg.state == 0 then
        logicMgr.CostManager.getFetchReward(msg.items);
    end
end
function costHandler.GetGrowthFreeRewardMsg(msg)
    if msg.state==0 then
        logicMgr.CostManager.getGrowthFreeReward()
    end
end

function costHandler.GetCurrencyBuyReward(msg)
    if msg.state == 0 then
        logicMgr.CostManager.getFetchRewardNew(msg.items);
    end
end

function costHandler.GetBuyCostMsg(msg)
    if msg.state == 0 then
        logicMgr.CostManager.UpdateOneCostServerData(msg.marketData)
    end
end

function costHandler.GetPayGradeMsg(msg)
    if msg.state == 0 then
        logicMgr.CostManager.setPlayerConsumeClass(msg.grade)
        logicMgr.CostManager.setPlayerRechargeNum(msg.isRecharge)
        logError("当前用户消费等级:"..tostring(msg.grade));
        FireEvent(Config.EventType.UICostUpdate, 1);
    end
end

--创建订单时记录
function costHandler.RecordOrder(data)
    local t = {}
    --t.order_id = data
    t.product_id        = data.productId
    t.productid_u8      = data.productIdU8
    t.recharge_amount   = data.price
    t.source            = data.source and data.source or -1
    t.pay_way           = -1
    t.info_ex           = -1
    t.pay_level         = data.vip
    t.extension         = data.extension

    costHandler.order_info = t
end

function costHandler.GetOrderInfo()
    return costHandler.order_info
end

function costHandler.GetSdkBuyCostMsg(msg)
     if msg.state == 0 then
         local msgData = msg.payParams;
         if msgData == nil then
             return;
         end
         local data = {};
         data.productId = msgData.productId;
         data.productName = getLanguage(msgData.productName or "");
         data.productDesc = getLanguage(msgData.productDesc or "");
         data.price = msgData.price;
         data.buyNum = msgData.buyNum;
         data.coinNum = msgData.coinNum;
         data.serverId = msgData.serverId;
         data.serverName = msgData.serverName;
         data.roleId = msgData.roleId;
         data.roleName = msgData.roleName;
         data.roleLevel = msgData.roleLevel;
         data.vip = msgData.vip;
         data.payNotifyUrl = msgData.payNotifyUrl;
         data.extension = msgData.extension;
         data.productIdU8 = msgData.productIdU8;
         --local data2 = {}
         --data2.extension = msgData.extension;
         --data2.roleID = msgData.roleId;
         --local data3 = getJsonStr(data2);
         --WebMsgMgr:SendHttpRequest(msgData.payNotifyUrl, data3, function (xx)
         --    local data = xx;
         --end);
         if Application.platform == RuntimePlatform.Android and Config.isOpenSDK then 
            logicMgr.SDKManager.Pay(data.productIdU8, data.productName, data.productDesc, data.price, data.buyNum, data.coinNum, data.serverId, data.serverName, data.roleId, data.roleName, data.roleLevel, data.vip, data.payNotifyUrl, data.extension);
         elseif Application.platform == RuntimePlatform.IPhonePlayer and Config.isOpenSDK then --IOS支付时需要用productId区分不同计费点
            logicMgr.SDKManager.Pay(data.productId, data.productName, data.productDesc, data.price, data.buyNum, data.coinNum, data.serverId, data.serverName, data.roleId, data.roleName, data.roleLevel, data.vip, data.payNotifyUrl, data.extension);
        else
            logicMgr.SDKManager.Pay(data.productIdU8, data.productName, data.productDesc, data.price, data.buyNum, data.coinNum, data.serverId, data.serverName, data.roleId, data.roleName, data.roleLevel, data.vip, data.payNotifyUrl, data.extension);
         end
        --{"gameUrl":"http://172.16.32.166:12015/api/deliverGoods/","id":263882857776069,"params":[102011],"marketId":10201}
        
         local _payDic = {}
         _payDic.product_id = tostring(msgData.productId)
         _payDic.productid_u8 = tostring(data.productIdU8)
         _payDic.recharge_amount = tonumber(msgData.price) * tonumber(msgData.buyNum)

         local extension_data = decodeJsonStrToTabel(msgData.extension)
         if extension_data then
            data.source = extension_data.marketId
            _payDic.source = tostring(extension_data.marketId)
         end

         costHandler.RecordOrder(data)
         
         TAManager.TrackByDictionary("order_init",_payDic)
     --else
         --UISysTips.AddMsg("订单发起失败");
         --UISysTips.AddMsgErrorCode(msg.state)
     end
end

function costHandler.GetPayNotifyDeliverMsg(msg)
    -- msg.orderId : 订单id
    if msg.state == 0 then
        msg.orderId = tonumber(tostring(msg.orderId)); -- 订单id
        msg.productId = msg.productId;   -- 商品id
        msg.source = msg.source; -- 模块来源
        msg.params = msg.params or ""; -- 额外参数

        local _payDic = {}--用户订单到货埋点
        
        _payDic.order_id        = string.format("%d", msg.orderId)--tostring会用科学计数法
        _payDic.product_id      = tostring(msg.productId)
        _payDic.source          = msg.source or ""
        _payDic.info_ex         = msg.params or ""

        local pay_config = G.dataTable["t_pay"][tostring(msg.productId)]
        if pay_config then
            _payDic.product_name = getLanguage(pay_config.f_ProductName)
            _payDic.recharge_amount = pay_config.f_Price
            _payDic.productid_u8 = tostring(pay_config.f_ProductIdU8)

            local info = costHandler.GetOrderInfo()
            if info then
                info.order_id = _payDic.order_id
                TAManager.TrackByDictionary("order_pay", info)
            end

            if tonumber(pay_config.f_Price) > 0 then
                TAManager.TrackByDictionary("order_product_achive", _payDic)
                if pay_config.f_BuyRecharge ~= nil and tonumber(pay_config.f_BuyRecharge) > 0 then
                    logicMgr.CostManager.UpdateVoucherRecharge(pay_config.f_Price);
                end
                if pay_config.f_CanActivateFirstRecharge ~= nil and tonumber(pay_config.f_CanActivateFirstRecharge) == 1 then
                    logicMgr.CostManager.setPlayerRechargeNum(1)
                end
            end

            TAManager.UserAdd("total_revenue", tonumber(pay_config.f_Price))
        end
        -- logError("order_id" .. tostring(msg.orderId))
        -- logError("order_id_TA" .. _payDic.order_id)
    end
end

function costHandler.GetVoucherData(msg)
    if msg.state == 0 then
        logicMgr.CostManager.SetVoucherData({ rewarded = msg.rewarded, recharge = tonumber(tostring(msg.recharge)) });
        FireEvent(Config.EventType.Fresh_FuncMenuData);
		FireEvent(Config.EventType.VoucherReward);
    end
end

function costHandler.GetFetchVoucherMsg(msg)
    if msg.state == 0 then
        logicMgr.CostManager.getFetchRewardModelId(msg.items);
        logicMgr.CostManager.SetVoucherData({ rewarded = 1, recharge = 0 });
        FireEvent(Config.EventType.Fresh_FuncMenuData);
		FireEvent(Config.EventType.VoucherReward);
    end
end

function costHandler.reqGetMarketInfo()
    local req = ReqSendMarketInfoMessage.New();
    sendReqMessage(req);
end

function costHandler.reqGetOneMarketInfo(id)
    local req = ReqOneMarketInfoMessage.New();
    req.marketID = tonumber(id);
    sendReqMessage(req);
end

function costHandler.reqGetFetchReward(id,index)
    local req = ReqFetchRewardMessage.New();
    req.marketID = id;
    req.params = index;
    sendReqMessage(req);
end

function costHandler.ReqCurrencyBuyReward(id,index)
    local req = ReqCurrencyBuyMessage.New();
    req.marketID = id;
    req.params = index;
    sendReqMessage(req);
end

function costHandler.reqGetGrowthFreeReward(id)
    local req=ReqGetGrowthFreeRewardMessage.New()
    req.rewardId=id
    sendReqMessage(req)
end

function costHandler.reqBuyCost(id, index, payId, num, type, giftId)
    local req = ReqCreatePayOrderMessage.New();
    req.productId = payId;
    req.extension = getJsonStr({modelId = id, params = index, type = type});
    req.channelId = tostring(Config.SDK_Channel);
    req.num = num or 1;
    req.subChannel = tonumber(Config.SDK_SubChannel) or 0
    req.os = SystemInfo.operatingSystem
    req.deviceId = SystemInfo.deviceUniqueIdentifier
    req.giftId = giftId or id;
    sendReqMessage(req);
end

function costHandler.reqCostBuyItem(id, index)
    local req = ReqBuyMessage.New();
    req.marketID = id;
    req.params = index;
    sendReqMessage(req);
end

function costHandler.reqCostChooseItem(id, index, itemList, assistId)
    local req = ReqChooseGiftMessage.New();
    req.marketID = tonumber(id);
    req.subId = tonumber(index);
    req.itemIdList = itemList;
    req.assistId = assistId or 0;
    sendReqMessage(req);
end

function costHandler.reqPayGrade()
    local req = ReqPayGradeMessage.New();
    sendReqMessage(req);
end

function costHandler.ReqVoucherData()
    if logicMgr.CostManager.HasVoucherReward() then
        local req = ReqVoucherDataMessage.New();
        sendReqMessage(req);
    end
end

function costHandler.ReqVoucherBuy(id, index, payId, num, type, coinType)
    local req = ReqVoucherBuyMessage.New();
    req.coinType = coinType;
    req.type = type;
    req.modelId = id;
    req.productId = payId;
    req.num = num or 1;
    req.params = index;
    sendReqMessage(req);

    TAManager.TrackByDictionary("cost_voucher", {modelId = id, productId = payId, num = num, coin_type = coinType})
end

function costHandler.ReqFetchVoucher()
    local req = ReqFetchVoucherMessage.New();
    sendReqMessage(req);
end

function costHandler.ReqPaySuccess(data)
    if true or data == nil then
        return ;
    end
    local req = ReqPaySuccessMessage.New();
    req.extension = data;
    sendReqMessage(req);
end